<template>
	<view>
		<picker mode="selector" :disabled="disabled" :value="pickerIndex" :range="list" :range-key="keyname" @change="handleChange">
			<view class="flex-ac">
				<input type="text" v-model="innerValue" disabled class="flex1" :placeholder="placeholder" placeholder-class="plStyle" style="pointer-events: none;opacity: 0;" />
				<text class="showname bgfff" v-if="!disabled" :class="{'plStyle':!innerName}">{{innerName||placeholder}}</text>
				<text class="showname bgfff" v-else>{{innerName||'-'}}</text>
				<text class="gui-icons f40 c999" v-if="!disabled">&#xe661;</text>
			</view>
		</picker>
	</view>
</template>

<script>
	export default {
		props: {
			value: {
				default: ''
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			list: {
				type: Array,
				default: () => []
			},
			keyname: {
				type: String,
				default: 'name'
			},
			valname: {
				type: String,
				default: 'val'
			},
			disabled: {
				type: Boolean,
				default: false
			},
		},
		watch: {
			value(val) {
				this.setDefault()
			}
		},
		data() {
			return {
				innerName:'',
				innerValue: '',
				pickerIndex:0
			}
		},
		created() {
			this.setDefault()
		},
		methods: {
			setDefault(){
				this.innerName = ''
				this.innerValue=''
				if(!this.value||!this.list.length) return;
				this.pickerIndex = this.list.findIndex(item=>item[this.valname]==this.value)
				this.innerName = this.list[this.pickerIndex][this.keyname]
				this.innerValue  =this.list[this.pickerIndex][this.valname]
			},
			handleChange(e) {
				let name = this.list[e.detail.value][this.keyname]
				let val = this.list[e.detail.value][this.valname]
				this.pickerIndex = e.detail.value
				this.innerName = name
				this.innerValue  = val
				this.$emit('input', val)
				this.$emit('change', val)
			}

		}
	}
</script>

<style scoped>
.showname{
	position: absolute;
	left: 0;
	width: 450rpx;
	overflow: hidden;
}
</style>